package com.wei.lawyer.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.BannerBean;
import com.wei.lawyer.model.BaseDataBean;
import com.wei.lawyer.model.HomeUtilsBean;
import com.wei.lawyer.model.LawyerBean;
import com.wei.lawyer.model.LawyerClassBean;
import com.wei.lawyer.net.contract.HomeView;
import com.wei.lawyer.net.presenter.HomePresenter;
import com.wei.lawyer.ui.activity.BookActivity;
import com.wei.lawyer.ui.activity.CaseActivity;
import com.wei.lawyer.ui.activity.CompanyActivity;
import com.wei.lawyer.ui.activity.CompanyDetailActivity;
import com.wei.lawyer.ui.activity.ContractActivity;
import com.wei.lawyer.ui.activity.FindActivity;
import com.wei.lawyer.ui.activity.LawyerActivity;
import com.wei.lawyer.ui.activity.LoginActivity;
import com.wei.lawyer.ui.activity.PhoneConsultingActivity;
import com.wei.lawyer.ui.activity.QuickConsultingActivity;
import com.wei.lawyer.ui.adapter.BaseAdapter;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.utils.ImageUtils;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;

/**
 * 作者：赵若位
 * 时间：2018/10/27 13:45
 * 邮箱：1070138445@qq.com
 * 功能：首页
 */
public class HomeFragment extends BaseFragment<HomePresenter> implements HomeView
{
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh)
    SmartRefreshLayout mRefresh;

    private DelegateAdapter mAdapter;
    private BaseDelegateAdapter mBannerAdapter, mServiceAdapter, mLawyerTitleAdapter, mLawyerAdapter, mClassAdapter, mUtilsAdapter;

    private static int mPage = 1;//法律小课堂


    @Override
    protected int getLayoutResource()
    {
        return R.layout.fragment_home;
    }

    @Override
    protected HomePresenter createPresenter()
    {
        return new HomePresenter(this, this);
    }


    @Override
    protected void initView()
    {
        super.initView();
        initRefreshListener();
        VirtualLayoutManager manager = new VirtualLayoutManager(mActivity);
        manager.setInitialPrefetchItemCount(3);
        mRecyclerView.setLayoutManager(manager);
        //关闭动效提升效率
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setItemViewCacheSize(3);

        mAdapter = new DelegateAdapter(manager, false);
        mRecyclerView.setAdapter(mAdapter);
        initAdapter();
    }

    /*初始化适配器*/
    private void initAdapter()
    {
        //初始化Banner适配器
        mBannerAdapter = new BaseDelegateAdapter<BaseDataBean<List<BannerBean>>>(mActivity, R.layout.layout_home_banner)
        {
            private ImageUtils mUtils = new ImageUtils(mActivity);
            private ImageLoader loader = new ImageLoader()
            {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView)
                {
                    BannerBean data = (BannerBean) path;
                    mUtils.setImageResource(data.getImageUrl(), imageView);
                }
            };

            @Override
            public void convert(BaseViewHolder holder, int position, BaseDataBean<List<BannerBean>> data)
            {
                holder.setOnClickListener(R.id.tv_quick, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //快速咨询
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(QuickConsultingActivity.class, null);
                    }
                }).setOnClickListener(R.id.tv_phone, new View.OnClickListener()//电话咨询
                {
                    @Override
                    public void onClick(View v)
                    {
                        //电话快问
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(PhoneConsultingActivity.class, null);
                    }
                });

                Banner banner = holder.getView(R.id.banner);
                banner.setImageLoader(loader);
                banner.setImages(data.getT() == null ? new ArrayList<BannerBean>() : data.getT());
                banner.start();
            }
        };
        mAdapter.addAdapter(mBannerAdapter);
        mBannerAdapter.setData(new BaseDataBean());

        //初始化服务适配器
        mServiceAdapter = new BaseDelegateAdapter<BaseDataBean<List<LawyerBean>>>(mActivity, R.layout.layout_home_service)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, BaseDataBean<List<LawyerBean>> data)
            {
                holder.setText(getString(R.string.tv_service_dynamic), R.id.item_title)
                        .setVisible(R.id.item_more, false)
                        .setOnClickListener(R.id.img_find, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                //找律师
                                openActivity(FindActivity.class, null);
                            }
                        }).setOnClickListener(R.id.img_case, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //案件委托
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(CaseActivity.class, null);
                    }
                }).setOnClickListener(R.id.tv_book, new View.OnClickListener()//文书服务
                {
                    @Override
                    public void onClick(View v)
                    {
                        //文书服务
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(BookActivity.class, null);
                    }
                }).setOnClickListener(R.id.tv_letter, new View.OnClickListener()//律师函
                {
                    @Override
                    public void onClick(View v)
                    {
                        //律师函
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(CompanyDetailActivity.class, null);
                    }
                }).setOnClickListener(R.id.tv_contract, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //合同模板
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(ContractActivity.class, null);
                    }
                }).setOnClickListener(R.id.tv_company, new View.OnClickListener()//企业服务
                {
                    @Override
                    public void onClick(View v)
                    {
                        //企业服务
                        if (mActivity.isFastDoubleClick()) return;
                        if (TextUtils.isEmpty(App.mToken))
                        {
                            openActivity(LoginActivity.class, null);
                            return;
                        }
                        openActivity(CompanyActivity.class, null);
                    }
                });

                RecyclerView recyclerView = holder.getView(R.id.recyclerView);
                LinearLayoutManager manager = new LinearLayoutManager(mActivity);
                recyclerView.setLayoutManager(manager);
                BaseAdapter adapter = new BaseAdapter<LawyerBean>(mActivity, R.layout.item_home_lawyer_service)
                {
                    @Override
                    public void convert(BaseViewHolder holder, int position, LawyerBean data)
                    {
                        holder.setCircleImageResource(data.getAvatar(), R.dimen.dp_30, R.id.item_image)
                                .setText(data.getNickName(), R.id.item_title)
                                .setText("完成了一次土地方面的咨询", R.id.item_descript)
                                .setText("2分钟前", R.id.item_time);
                    }
                };
                recyclerView.setAdapter(adapter);
                List<LawyerBean> list = data.getT();
                adapter.setData((list != null && list.size() > 2) ? list.subList(0, 2) : list);
            }
        };
        mAdapter.addAdapter(mServiceAdapter);
        mServiceAdapter.setData(new BaseDataBean());

        //初始化推荐律师标题
        mLawyerTitleAdapter = new BaseDelegateAdapter<String>(mActivity, R.layout.layout_home_title)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                holder.setText(getString(R.string.tv_recomment_lawyer), R.id.item_title)
                        .setVisible(R.id.item_more, true)
                        .itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        openActivity(FindActivity.class, null);
                    }
                });
            }
        };
        mAdapter.addAdapter(mLawyerTitleAdapter);
        mLawyerTitleAdapter.setData("");

        //推荐律师
        mLawyerAdapter = new BaseDelegateAdapter<LawyerBean>(mActivity, R.layout.item_find_lawyer)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, final LawyerBean data)
            {
                String[] label = data.getLabel();
                holder.setText(data.getNickName(), R.id.item_name)//律师名字
                        .setText(TextUtils.concat(mResources.getString(R.string.tv_worktime), data.getCareerTime()).toString(), R.id.item_workTime)//工作年限
                        .setText(data.getWorkAddress(), R.id.item_address)//工作地址
                        .setText(TextUtils.concat(mResources.getString(R.string.tv_money), data.getWorkPrice(), mResources.getString(R.string.tv_count)).toString(), R.id.item_price)//服务价格
                        .setText(data.getWorkType(), R.id.item_type)//职业类型
                        .setText(data.getStatus() == 2 ? mResources.getString(R.string.tv_online) : mResources.getString(R.string.tv_outLine), R.id.item_onLine)//当前是否在线
                        .setCircleImageResource(data.getAvatar(), R.dimen.dp_58, R.id.item_heade)
                        .itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Intent it = new Intent(mActivity, LawyerActivity.class);
                        it.putExtra(LawyerActivity.class.getSimpleName(), data);
                        mActivity.startActivity(it);
                    }
                });//律师头像

                /*设置律师当前是否在线*/
                TextView status = holder.getView(R.id.item_onLine);
                Drawable drawable = mResources.getDrawable(data.getStatus() == 2 ? R.mipmap.lawyer_online : R.mipmap.lawyer_busy);
                drawable.setBounds(0, 0,
                        mResources.getDimensionPixelOffset(R.dimen.dp_11),
                        mResources.getDimensionPixelOffset(R.dimen.dp_11));
                status.setCompoundDrawables(drawable, null, null, null);

                /*设置律师擅长的标签*/
                RecyclerView child = holder.getView(R.id.item_label);
                child.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
                BaseAdapter<String> adapter = new BaseAdapter<String>(mActivity, R.layout.item_find_lawyer_label)
                {
                    @Override
                    public void convert(BaseViewHolder holder, int position, String s)
                    {
                        holder.setText(s, R.id.item_title);
                    }
                };
                adapter.bindRecyclerView(child);
                adapter.setData((label == null || label.length == 0) ? null : Arrays.asList(label));
            }
        };
        mAdapter.addAdapter(mLawyerAdapter);

        //律师讲堂适配器
        mClassAdapter = new BaseDelegateAdapter<LawyerClassBean>(mActivity, R.layout.layout_home_class)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, LawyerClassBean data)
            {
                TextView tv_class = holder.getView(R.id.layout_class).findViewById(R.id.item_title);
                tv_class.setText("法律小讲堂");
                holder.getView(R.id.layout_class).findViewById(R.id.item_more).setVisibility(View.GONE);

                TextView tv_utils = holder.getView(R.id.layout_utils).findViewById(R.id.item_title);
                tv_utils.setText("实用小工具");
                holder.getView(R.id.layout_utils).findViewById(R.id.item_more).setVisibility(View.GONE);

                holder.setText(data.getTitle(), R.id.tv_title)
                        .setText(data.getContent(), R.id.tv_descript)
                        //换一条
                        .setOnClickListener(R.id.tv_next, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                mPage += 1;
                                mPresenter.getLawclassData(mPage);
                            }
                        });
            }
        };
        mAdapter.addAdapter(mClassAdapter);
        mClassAdapter.setData(new LawyerClassBean());

        //小工具适配器
        GridLayoutHelper helper = new GridLayoutHelper(3);
        helper.setAutoExpand(false);
        mUtilsAdapter = new BaseDelegateAdapter<HomeUtilsBean>(mActivity, R.layout.layout_home_utils)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, HomeUtilsBean data)
            {
                holder.setImageResource(data.getImageResource(), R.id.item_image)
                        .setText(data.getTitle(), R.id.item_title)
                        .setText(data.getDescript(), R.id.item_descript);
            }
        }.setLayoutHelper(helper);
        mAdapter.addAdapter(mUtilsAdapter);
        mUtilsAdapter.setData(HomeUtilsBean.getList());
    }


    /*设置刷新监听*/
    private void initRefreshListener()
    {
        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener()
        {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout)
            {
                mRefresh.finishLoadMore();
            }
        });

        mRefresh.setOnRefreshListener(new OnRefreshListener()
        {
            @Override
            public void onRefresh(RefreshLayout refreshLayout)
            {
                initData();
                //刷新三秒自动关闭
                mRefresh.finishRefresh(2000);
            }
        });
    }


    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getBannerData();
        mPresenter.getLawyerServiceData();
        mPresenter.getLawyerRecommentData();
        mPresenter.getLawclassData(mPage);
    }


    @Override
    public void showBannerData(BaseDataBean<List<BannerBean>> data)
    {
        mBannerAdapter.setData(data);
    }

    @Override
    public void showServiceData(BaseDataBean<List<LawyerBean>> data)
    {
        mServiceAdapter.setData(data);
    }

    @Override
    public void showRecommentData(List<LawyerBean> list)
    {
        mLawyerAdapter.setData((list != null && list.size() >= 3) ? list.subList(0, 3) : list);
    }

    @Override
    public void showLawClassData(LawyerClassBean data)
    {
        if (data == null)
        {
            mPage = 1;
        }
        mClassAdapter.setData(data);
    }
}














































